using Microsoft.EntityFrameworkCore;
using UniversalAdmin.Domain.Entities.App;
namespace UniversalAdmin.Infrastructure.Data.Contexts
{



  public class AdminDbContext(DbContextOptions<AdminDbContext> options) : DbContext(options)
    {
        public DbSet<AppUser> AppUsers { get; set; } = null!;
        public DbSet<AppFile> AppFiles { get; set; } = null!;
        public DbSet<AppOperationLog> AppOperationLogs { get; set; } = null!;
        public DbSet<AppPermission> AppPermissions { get; set; } = null!;
        public DbSet<AppMenu> AppMenus { get; set; } = null!;
        public DbSet<AppRole> AppRoles { get; set; } = null!;
        public DbSet<AppSystemConfig> AppSystemConfigs { get; set; } = null!;
     

        protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      // 应用DDD命名规则
      ApplyDddNamingConventions(modelBuilder);

      // 显式指定多对多中间表名，避免表名冲突
      modelBuilder.Entity<AppRole>()
          .HasMany(r => r.Permissions)
          .WithMany(p => p.Roles)
          .UsingEntity(j => j.ToTable("RolePermissions"));

      modelBuilder.Entity<AppRole>()
          .HasMany(r => r.Menus)
          .WithMany(m => m.Roles)
          .UsingEntity(j => j.ToTable("RoleMenus"));

      modelBuilder.Entity<AppUser>()
          .HasMany(u => u.Roles)
          .WithMany(r => r.Users)
          .UsingEntity(j => j.ToTable("UserRoles"));

      base.OnModelCreating(modelBuilder);
    }

    /// <summary>
    /// 应用DDD命名规则
    /// </summary>
    /// <param name="modelBuilder"></param>
    private static void ApplyDddNamingConventions(ModelBuilder modelBuilder)
    {
      // 遍历所有实体类型
      foreach (Microsoft.EntityFrameworkCore.Metadata.IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes())
      {
        // 表名：移除"App"前缀，使用复数形式
        string tableName = entityType.ClrType.Name;
        if (tableName.StartsWith("App"))
        {
          tableName = tableName[3..];
        }
        // 转换为复数形式（简单实现，实际项目可能需要更复杂的处理）
        if (!tableName.EndsWith("s"))
        {
          tableName += "s";
        }
        entityType.SetTableName(tableName);

        // 列名：使用下划线命名法
        foreach (Microsoft.EntityFrameworkCore.Metadata.IMutableProperty property in entityType.GetProperties())
        {
          string columnName = property.Name;
          // 驼峰转下划线
          columnName = string.Concat(columnName.Select(static (c, i) => i > 0 && char.IsUpper(c) ? "_" + c.ToString().ToLower() : c.ToString().ToLower()));
          property.SetColumnName(columnName);
        }
      }
    }


   

  }
}